package com.jasonjan.jiance.module.search.listview;

import android.util.Log;

import com.jasonjan.jiance.api.IHomeApi;
import com.jasonjan.jiance.bean.HomeNews;
import com.jasonjan.jiance.global.Constant;
import com.jasonjan.jiance.global.ErrorAction;
import com.jasonjan.jiance.global.RetrofitFactory;
import com.jasonjan.jiance.util.MD5Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by jasonjan on 2018/3/13.
 */

public class SearchLessonPresenter implements ISearchView.Presenter {

    private static final String TAG = "SearchLessonPresenter";
    private ISearchView.View view;
    private List<HomeNews.ResultBean.DataBean> dataList = new ArrayList<>();
    private String category;
    private int pageIndex=0;

    SearchLessonPresenter(ISearchView.View view) {
        this.view = view;
    }

    @Override
    public void doLoadData(String... category) {

        try {
            if (null == this.category) {
                this.category = category[0];
            }
        } catch (Exception e) {
            ErrorAction.print(e);
        }

        // 释放内存
        if (dataList.size() > 100) {
            dataList.clear();
        }
        Log.d("\n请求：","category==>"+this.category+"  pageIndex="+pageIndex+" pageSize="+Constant.PAGESIZE+" sign="+MD5Util.md5(Constant.salt)+"\n");

        if(this.category.equals("news")){
            requestHomeTitle();
        }else if(this.category.equals("lesson")){
            requestHomeClass();
        }

    }

    public void requestHomeTitle(){
        //构造请求参数
        JSONObject requestJson=new JSONObject();
        try{
            requestJson.put("pageIndex",this.pageIndex);
            requestJson.put("pageSize", Constant.PAGESIZE);
            requestJson.put("school","广州大学");
            requestJson.put("token","");
            requestJson.put("sign",MD5Util.md5(Constant.salt));
        }catch (JSONException e){
            e.printStackTrace();
        }
        RequestBody body= RequestBody.create(MediaType.parse(Constant.Content_Type),requestJson.toString());
        RetrofitFactory.getRetrofit().create(IHomeApi.class).getGuidance(body)
                .subscribeOn(Schedulers.io())
                .switchMap(new Function<HomeNews, Observable<HomeNews.ResultBean.DataBean>>() {
                    @Override
                    public Observable<HomeNews.ResultBean.DataBean> apply(@NonNull HomeNews homeNews) throws Exception {

                        List<HomeNews.ResultBean.DataBean> data = homeNews.getResult().getData();
                        // 移除最后一项 数据有重复
                        if (data.size() > 0)
                            data.remove(data.size() - 1);

                        return Observable.fromIterable(data);
                    }
                })
                .filter(new Predicate<HomeNews.ResultBean.DataBean>() {
                    @Override
                    public boolean test(@NonNull HomeNews.ResultBean.DataBean dataBean) throws Exception {
                        // 去除重复新闻
                        for (HomeNews.ResultBean.DataBean bean : dataList) {
                            if (dataBean.getTitle().equals(bean.getTitle())) {
                                return false;
                            }
                        }
                        return true;
                    }
                })
                .toList()
                .compose(view.<List<HomeNews.ResultBean.DataBean>>bindToLife())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<HomeNews.ResultBean.DataBean>>() {
                    @Override
                    public void accept(@NonNull List<HomeNews.ResultBean.DataBean> list) throws Exception {
                        if (null != list && list.size() > 0) {
                            doSetAdapter(list);
                        } else {
                            doShowNoMore();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        doShowNetError();
                        ErrorAction.print(throwable);
                    }
                });
    }

    public void requestHomeClass(){
        //构造请求参数
        JSONObject requestJson=new JSONObject();
        try{
            requestJson.put("pageIndex",this.pageIndex);
            requestJson.put("pageSize", Constant.PAGESIZE);
            requestJson.put("school","广州大学");
            requestJson.put("token","");
            requestJson.put("sign",MD5Util.md5(Constant.salt));
        }catch (JSONException e){
            e.printStackTrace();
        }
        RequestBody body= RequestBody.create(MediaType.parse(Constant.Content_Type),requestJson.toString());
        RetrofitFactory.getRetrofit().create(IHomeApi.class).getSummary(body)
                .subscribeOn(Schedulers.io())
                .switchMap(new Function<HomeNews, Observable<HomeNews.ResultBean.DataBean>>() {
                    @Override
                    public Observable<HomeNews.ResultBean.DataBean> apply(@NonNull HomeNews homeNews) throws Exception {

                        List<HomeNews.ResultBean.DataBean> data = homeNews.getResult().getData();
                        // 移除最后一项 数据有重复
                        if (data.size() > 0)
                            data.remove(data.size() - 1);

                        return Observable.fromIterable(data);
                    }
                })
                .filter(new Predicate<HomeNews.ResultBean.DataBean>() {
                    @Override
                    public boolean test(@NonNull HomeNews.ResultBean.DataBean dataBean) throws Exception {
                        // 去除重复新闻
                        for (HomeNews.ResultBean.DataBean bean : dataList) {
                            if (dataBean.getTitle().equals(bean.getTitle())) {
                                return false;
                            }
                        }
                        return true;
                    }
                })
                .toList()
                .compose(view.<List<HomeNews.ResultBean.DataBean>>bindToLife())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<HomeNews.ResultBean.DataBean>>() {
                    @Override
                    public void accept(@NonNull List<HomeNews.ResultBean.DataBean> list) throws Exception {
                        if (null != list && list.size() > 0) {
                            doSetAdapter(list);
                        } else {
                            doShowNoMore();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        doShowNetError();
                        ErrorAction.print(throwable);
                    }
                });
    }

    @Override
    public void doLoadMoreData() {
        pageIndex++;
        doLoadData();
    }

    @Override
    public void doSetAdapter(List<HomeNews.ResultBean.DataBean> dataBeen) {
        dataList.addAll(dataBeen);
        view.onSetAdapter(dataList);
        view.onHideLoading();
    }

    @Override
    public void doRefresh() {
        if (dataList.size() != 0) {
            dataList.clear();
        }
        view.onShowLoading();
        pageIndex=0;
        doLoadData();
    }

    @Override
    public void doShowNetError() {
        view.onHideLoading();
        view.onShowNetError();
    }

    @Override
    public void doShowNoMore() {
        view.onHideLoading();
        view.onShowNoMore();
    }
}
